package com.jie.barcode.demo

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.ToastUtils
import com.jie.barcode.demo.databinding.ActivityQrCodeViewBinding

/**
 * 使用CameraX预览摄像头，并解析二维码
 * 使用 QRCodeView 处理扫码逻辑
 */
open class QRCodeScanViewActivity : AppCompatActivity() {

    private lateinit var mViewBinding : ActivityQrCodeViewBinding

    /**
     * 图片选择结果回调
     */
    private val mPictureChooseLauncher = registerForActivityResult(ActivityResultContracts.GetContent()){
        it?.let {
            mViewBinding.qrCodeView.process(it)
        }
    }

    /**
     * 权限申请结果回调
     */
    private val mPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
        if (it){ // 权限申请成功
            openCamera()
        } else { // 缺少摄像头权限
            ToastUtils.showShort("缺少摄像头权限")
            finish()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewBinding = ActivityQrCodeViewBinding.inflate(layoutInflater)
        setContentView(mViewBinding.root)
        initActionBar()
        initEvent()
        checkPermissionAndOpenCamera()
    }

    /**
     * 校验摄像头权限，若有权限则打开摄像头，若没有权限则申请权限
     */
    private fun checkPermissionAndOpenCamera() {
        // 校验摄像头权限
        val cameraPermission = Manifest.permission.CAMERA
        if (ContextCompat.checkSelfPermission(
                this,
                cameraPermission
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            openCamera()
        } else {
            mPermissionLauncher.launch(cameraPermission)
        }
    }

    /**
     * 初始化ActionBar
     */
    private fun initActionBar() {
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setTitle(R.string.app_name)
    }

    /**
     * 设置actionbar左上角箭头返回
     */
    override fun onSupportNavigateUp(): Boolean {
        onBackPressedDispatcher.onBackPressed()
        return super.onSupportNavigateUp()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menu?.add(MENU_GROUP_ID, MENU_ITEM_ID_CHOOSE_PICTURE, MENU_ITEM_ID_CHOOSE_PICTURE, R.string.menu_choose_picture)
        menu?.add(MENU_GROUP_ID, MENU_ITEM_ID_OLD_SCAN, MENU_ITEM_ID_OLD_SCAN, R.string.menu_scan_old)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == MENU_ITEM_ID_CHOOSE_PICTURE) {
            mPictureChooseLauncher.launch("image/*")
        } else if (item.itemId == MENU_ITEM_ID_OLD_SCAN) {
            startActivity(Intent(this, QRCodeScanActivity::class.java))
        }
        return super.onOptionsItemSelected(item)
    }

    /**
     * 初始化组件的事件
     */
    private fun initEvent() {
        mViewBinding.run {
            qrCodeView.apply {
                mSuccessListener = {
                    showResultDialog(it)
                }
                mFailureListener = {
                    ToastUtils.showShort("解析出错了")
                }
            }
        }
    }

    /**
     * 显示扫码结果Dialog
     */
    private fun showResultDialog(result : String) {
        QRCodeResultDialog().run {
            resultStr = result
            againstStr = StringUtils.getString(R.string.show_result)
            exitStr = StringUtils.getString(R.string.against)
            againstListener = {
//                mViewBinding.qrCodeView.startAnalysis()
                startActivity(Intent(this@QRCodeScanViewActivity, OtherPageActivity::class.java).apply {
                    putExtra(PARAM_RESULT, result)
                })
            }
            exitListener = {
                mViewBinding.qrCodeView.startAnalysis()
            }
            show(supportFragmentManager, this.toString())
        }
    }

    /**
     * 打开摄像头并开始扫码
     */
    private fun openCamera() {
        mViewBinding.qrCodeView.startCamera()
    }

    companion object{
        // 菜单相关常量值
        const val MENU_GROUP_ID = 0x001
        const val MENU_ITEM_ID_CHOOSE_PICTURE = 0x001
        const val MENU_ITEM_ID_OLD_SCAN = 0x002
        // 扫码结果
        const val PARAM_RESULT = "PARAM_RESULT"
    }
}